<template>
  <div id="home">
    <div class="title" v-if="isShowTitle == 'display'">
      <input class="uni-input" v-model="title" placeholder="标题（18字以内阅读效果更佳）" />
    </div>
    <editor id="editor" ref="editor" v-model="content" api-key="rvfc0ay2ccqszix6wo8aqgzl3inpyvrhor0a1gpt8jalaomt"
      :init="options" />
    <Cover v-if="isShowThumbnail && isShowThumbnail != 'false'" :thumbnail="thumbnail" @delThumbnail="delThumbnail" />
    <AddLink :isShowLink="isShowLink" :duration="duration" @cancel="cancel" @confirm="confirm" />
    <SetColor :isShowColor="isShowColor" :duration="duration" @confirm="finish" @cancel="colorCancel" />
    <SetFont ref="setFont" :isShowFont="isShowFont" :duration="duration" @confirm="setFont" @cancel="fontCancel" />
    <div class="toolbar-foot tox-toolbar-overlord" ref="toolbar-foot">
      <van-cell title="图片设置" is-link @click.native="setImg" v-show="!isShowLink" />
      <div class="toolbar" v-show="!isShowLink">
        <div class="toolbar-item" @click="showColor">
          <img src="@/assets/img/color.png" alt="" />
        </div>
        <div class="toolbar-item" @click="showFont">
          <img src="@/assets/img/font.png" alt="" />
        </div>
        <div class="toolbar-item" @click="checkImage">
          <img src="@/assets/img/image.png" alt="" />
        </div>
        <div class="toolbar-item" @click="JumpTopic" v-if="isShowTitle == 'display'">
          <img src="@/assets/img/well.png" alt="" />
        </div>
        <div class="toolbar-item" @click="showPopup">
          <img src="@/assets/img/link.png" alt="" />
        </div>
        <div class="toolbar-item" @click="JumpUser">
          <img src="@/assets/img/at.png" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import tinymce from "tinymce/tinymce";
import Cover from "@/components/cover";
import AddLink from "@/components/add-link";
import SetColor from "@/components/set-color";
import SetFont from "@/components/set-font";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver/theme";
import "tinymce/skins/ui/oxide/skin.min.css";
import "tinymce/icons/default/icons.min.js";
import "tinymce/skins/content/default/content.css";
import "tinymce/themes/mobile";
import MonitorKeyboard from "@/assets/js/keyBoard";
import $ from "jquery";
export default {
  name: "home",
  components: {
    editor: Editor,
    Cover,
    AddLink,
    SetColor,
    SetFont,
  },
  data() {
    return {
      title: "",
      thumbnail: "",
      content: "",
      // is_watermark: 1,
      isShowThumbnail: false,
      isShowTitle: 'display',
      // isShowWater: false,
      at: [], //@人的集合
      hot_id: [], //相关话题的集合
      monitorKeyboard: null,
      isShowLink: false,
      isShowColor: false,
      isShowFont: false,
      keyboardHeight: 0,
      duration: 0.3,
      editor: null,
      options: {
        selector: "textarea",
        noneditable_class: "mceNonEditable",
        base_url: "tinymce",
        language: "zh_CN",
        language_url: "tinymce/langs/zh_CN.js", //语言文件
        skin_url: "tinymce/skins/ui/oxide",
        images_upload_url: "",
        convert_urls: false, //关闭路径自动补全
        content_style:
          "img {width: 100%;object-fit:cover} .mceNonEditable {color:#025CE0!important;} .mce-content-body[data-mce-placeholder]:not(.mce-visualblocks)::before {color: #dedede;font-size:14px} blockquote{display: block;border-left: 8px solid #d0e5f2;padding: 5px 10px;margin: 10px 0!important;line-height: 1.4;font-size: 100%;background-color: #f1f1f1!important;}",
        placeholder: "",
        icons_url:
          "https://upload.zhongsheyun.com/5iDwTj4QTjH3UU9hi6JI9S/1659518098319881.js", // load icon pack
        icons: "jinshi",
        mobile: {
          menubar: false,
          statusbar: false,
          quickbars_insert_toolbar: false,
          end_container_on_empty_block: true,
          toolbar_mode: "floating",
          toolbar_location: "bottom",
          toolbar_sticky: true,
          toolbar_sticky_offset: 100,
          image_caption: true, //图片的标题
          image_dimensions: false,
          image_title: false,
          image_description: false,
          image_uploadtab: true, //允许您上传本地图像
          // paste_data_images: true,//启用拖入上传则需要设置为true
          // images_file_types: 'jpeg,jpg,png,gif,bmp,webp', //允许拖入的图片后缀
          image_advtab: true, //“高级”选项卡图像添加自定义样式、间距和边框
          external_plugins: {
            //引入需要的插件
            lists: "tinymce/plugins/lists/plugin.min.js",
            imagetools: "tinymce/plugins/imagetools/plugin.min.js",
            textpattern: "tinymce/plugins/textpattern/plugin.min.js",
            noneditable: "tinymce/plugins/noneditable/plugin.min.js",
            preview: "tinymce/plugins/preview/plugin.min.js",
            autoresize: "/tinymce/plugins/autoresize/plugin.min.js",
          },
          plugins: "noneditable autoresize paste", //imagetools 编辑图片
          paste_auto_cleanup_on_paste: true,
          paste_remove_styles: true,
          paste_remove_styles_if_webkit: true,
          paste_strip_class_attributes: true,
          paste_as_text: true,
          min_height: 300,
          toolbar: false,
          target_list: false,
          toolbar_persist: false, //当开启后内联模式下将始终显示工具栏和菜单栏，而不是在失去焦点时隐藏他们
        },
        setup: (editor) => {
          this.editor = editor;
          let that = this;
          editor.on("init", function (event) { });
          editor.on("NodeChange", function (e) {
            // console.log("change event", 2, e);
            if (e.parents.length) {
              if (e.parents.every((ele) => ele.localName !== "blockquote")) {
                that.$refs["setFont"].cancelBlockquote(0);
              } else {
                that.$refs["setFont"].cancelBlockquote(1);
              }
              if (e.parents.every((ele) => ele !== "li")) {
                that.$refs["setFont"].cancelUlOl();
              }
              if (e.parents[0].localName == "li") {
                if (e.parents[1].localName == "ol") {
                  that.$refs["setFont"].cancelLi(1);
                } else if (e.parents[1].localName == "ul") {
                  that.$refs["setFont"].cancelLi(0);
                }
              }
            }
          });
          editor.on("KeyDown", function (e) {
            if ((e.keyCode == 8 || e.keyCode == 46) && editor.selection) {
              // var selectedNode = editor.selection.getNode(); // get the selected node (element) in the editor
              // console.log('selectedNode,selectedNode',selectedNode,selectedNode.nodeName)
              // if (selectedNode && selectedNode.nodeName == "IMG") {
              //   that.delImageCallBack(selectedNode.src);
              // }
            }
          });
        },
      },
    };
  },
  created() {
    this.isShowThumbnail = this.$route.query.showThumbnail;
    this.isShowTitle = this.$route.query.isShowTitle || 'display';
    this.options.placeholder = this.$route.query.placeholder || '请输入正文';
  },
  watch: {
    $route: {
      handler(newVal, oldVal) {
        console.log(newVal)
      },
    },
    title(newVal) {
      this.setH5ContentChanged();
    },
    content(newVal) {
      this.setH5ContentChanged();
    },
    thumbnail(newVal) {
      this.setH5ContentChanged();
    },
  },
  mounted() {
    window.onHrefPicked = this.onHrefPicked; //插入@ #
    window.onMediaFilePicked = this.onMediaFilePicked; //文件插入
    window.onThumbnailPicked = this.onThumbnailPicked; //封面图
    window.onMediaFilePicked = this.onMediaFilePicked; //富文本图
    window.getH5Content = this.getH5Content;
    window.setH5Content = this.setH5Content;
    this.getKeyboardState();
  },
  beforeDestroy() {
    this.monitorKeyboard.onEnd();
  },
  destroyed() {
    this.destroyTinymce();
  },
  methods: {
    //设置图片水印
    setImg() {
      // this.isShowWater = true;
      Android.openWatermarkSetting();
    },
    destroyTinymce() {
      this.editor.destroy();
    },
    //重新编辑内容h5获取内容 安卓调用
    setH5Content(title, content, thumbnail_path) {
      this.title = title || '';;
      this.content = content || '';
      this.thumbnail = thumbnail_path || '';
    },
    //安卓实时获取h5内容
    setH5ContentChanged() {
      if (!this.isShowThumbnail || this.isShowThumbnail == 'false') {
        this.thumbnail = ""
      }
      Android.setH5ContentChanged(
        this.title,
        this.content,
        this.thumbnail
      );
    },
    //安卓发布获取h5内容发布
    getH5Content() {
      this.hot_id = [];
      this.at = [];
      let AList = this.getObjectKeys(
        this.editor.getContent().match(/<a[^>]*['"]*>/g)
      );
      let linkList = [];
      AList.map((e, i) => {
        e.replace(
          /<a [^>]*href=['"]([^'"]+)[^>]*>/gi,
          function (match, capture) {
            linkList.push(capture);
          }
        );
      });
      linkList.forEach((e) => {
        if (e.indexOf("home/topic-details?id=") >= 0) {
          this.hot_id.push(e.split("?id=")[1]);
        } else if (e.indexOf("user-center/page?id=") >= 0) {
          this.at.push(e.split("?id=")[1]);
        }
      });
      Android.setH5Content(
        this.title,
        this.editor.getContent(),
        this.thumbnail,
        this.hot_id,
        this.at
      );
    },
    getObjectKeys(object) {
      var values = [];
      for (var property in object) values.push(object[property]);
      return values;
    },
    //安卓调用获取封面图路径
    onThumbnailPicked(mediafile) {
      this.thumbnail = mediafile;
    },
    //删除封面图
    delThumbnail(e) {
      this.thumbnail = e;
    },
    onHrefPicked(data, id, type) {
      this.editor.execCommand("mceInsertContent", false, data);
    },
    //显示颜色
    showColor() {
      this.duration = 0.3;
      this.isShowColor = true;
    },
    //选择颜色
    finish(e) {
      this.colorCancel();
      const color = e;
      if (!color) {
        return this.editor.execCommand("mceRemoveTextcolor", "forecolor");
      }
      this.editor.execCommand("mceApplyTextcolor", "forecolor", color);
    },
    //关闭颜色弹窗
    colorCancel() {
      this.duration = 0;
      this.isShowColor = false;
    },
    //显示文本
    showFont() {
      this.duration = 0.3;
      this.isShowFont = true;
    },
    //setFont设置文本类型
    setFont(e) {
      this.duration = 0;
      if (e == "InsertUnorderedList") {
        this.editor.execCommand("InsertUnorderedList", false, {
          "list-style-type": "disc",
          "list-item-attributes": { class: "mylistitemclass" },
          "list-attributes": { id: "mylist" },
        });
      } else if (e == "InsertDefinitionList") {
        this.editor.execCommand("InsertDefinitionList", false, {
          "list-item-attributes": { class: "mylistitemclass" },
          "list-attributes": { id: "mylist" },
        });
      } else {
        this.editor.execCommand(e, true);
      }
      this.isShowFont = false;
    },
    //关闭设置文本类型
    fontCancel() {
      this.duration = 0;
      this.isShowFont = false;
    },
    //显示链接弹窗
    showPopup() {
      this.duration = 0.3;
      this.isShowLink = true;
    },
    //添加链接
    confirm(e) {
      this.duration = 0;
      this.editor.execCommand(
        "mceInsertContent",
        false,
        `<a style="color: #025ce0" class="mceNonEditable" href="${e.link}">${e.linkName}</a>`
      );
      this.isShowLink = false;
    },
    //关闭链接弹窗
    cancel() {
      this.duration = 0;
      this.isShowLink = false;
    },
    beforeClose(action, done) {
      done(false);
    },
    //选择图片
    checkImage() {
      Android.pickMediaFile();
    },
    //拿到图片
    onMediaFilePicked(img) {
      this.onHrefPicked(`<p><img src="${img}" alt="" width="100%" height="" /></p>`);
    },
    //删除图片
    delImageCallBack(src) {
      console.log(src);
    },
    //跳转到话题
    JumpTopic() {
      Android.jumpPickTopic();
    },
    //跳转到@人列表
    JumpUser() {
      Android.jumpPickUser();
    },
    getKeyboardState() {
      let that = this;
      that.monitorKeyboard = new MonitorKeyboard();
      that.monitorKeyboard.onStart();

      // 监听虚拟键盘弹出事件
      that.monitorKeyboard.onShow(() => {
        $(".toolbar-foot").css("bottom", this.keyboardHeight);
        this.duration = 0;
        this.isShowColor = false;
        this.isShowFont = false;
        $(".toolbar-foot").show();
      });

      //监听键盘收起的事件
      that.monitorKeyboard.onHidden(() => {
        $(".toolbar-foot").hide();
      });
    },
  },
};
</script>
<style lang="scss" >
@import "./Home.scss";
</style>